package com.llmcu.tuling.architect.concurrent.countdownlatchsemaphore;

import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch 通常用法
 *
 * @author liuling
 * @date 2024/9/16 17:40
 */
public class CountDownLatchNormalUsage {
    public static void main(String[] args) throws InterruptedException {
        int threadCount = 3;
        CountDownLatch latch = new CountDownLatch(threadCount);

        for (int i = 0; i < threadCount; i++) {
            new Thread(new Worker(latch)).start();
        }

        // 主线程等待所有工作线程完成
        latch.await();
        System.out.println("所有工作线程已完成");
    }
}

class Worker implements Runnable {
    private final CountDownLatch latch;

    Worker(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        try {
            // 模拟工作线程的任务
            Thread.sleep((long) (Math.random() * 10000));
            System.out.println(Thread.currentThread().getName() + " 完成任务");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            latch.countDown();
        }
    }
}
